package com

import (
	"github.com/valyala/fasthttp"
	"log"
	"strings"
	"sync"
	"time"
	"encoding/json"
)

type NodeAnnounce struct {
	Action         string     `json:"action"`
	Timeout        int64      `json:"timeout"`
	Nat            int64      `json:"nat"`
	Time           int64      `json:"time"`
	PeerId         string     `json:"peer_id"`
	PredictionPort int        `json:"prediction_port"`
	Proto          int32      `json:"protocol"`
	Sdps           []NodeSdps `json:"sdps"`
}

type NodeSdps struct {
	Offer         NodeOffer `json:"offer"`
	OfferId       int64     `json:"offer_id"`
	RemoteOfferId int64     `json:"remote_offer_id"`
}
type NodeOffer struct {
	Type string `json:"type"`
	Sdp  string `json:"sdp"`
}

type NodeHost struct {
	Time     int64
	PeerId   string
	Host     string
	Announce *NodeAnnounce
}

var hostPool = &sync.Pool{
	New: func() interface{} {
		return &NodeHost{}
	},
}

func (a *NodeHost) Reset() {
	a.Host = a.Host[0:0]
	a.PeerId = a.PeerId[0:0]
	a.Announce = nil
}
func NewHost() *NodeHost {
	host := hostPool.Get().(*NodeHost)
	return host
}

func (a *NodeHost) Handle(nodes *Nodes, ctx *fasthttp.RequestCtx) {
	a.Time = time.Now().Unix()
	a.Host = string(ctx.QueryArgs().Peek("server"))
	a.PeerId = string(ctx.QueryArgs().Peek("node"))
	body := ctx.Request.Body()
	var announce = &NodeAnnounce{}
	if err := json.Unmarshal(body, announce); err == nil {
		a.Announce = announce
		nodes.lock.Lock()
		nodes.Host[strings.ToLower(a.PeerId)] = *a
		nodes.lock.Unlock()
	} else {
		log.Printf("[err]:when json decode node annouce:-->%v", err)
		return
	}
}
